<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="resData"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template #menu="{ row, index, size }">
        <el-button type="text" @click="handleView(row, index)">详情</el-button>
        <el-button type="text" @click="handMessage(row, index)"
          >聊天记录</el-button
        >
      </template>

      <template slot-scope="{ row }" slot="ReviewStatus">
        <p v-if="row.ReviewStatus == 0" class="blue-normal">进行中</p>
        <p v-else-if="row.ReviewStatus == 1" class="green-normal">已完成</p>
        <p v-else-if="row.ReviewStatus == 2">
          <span class="gray-normal">已下架</span>
        </p>
        <p v-else-if="row.ReviewStatus == 3" class="purple-normal">
          已完成（待支付）
        </p>
        <p v-else="row.ReviewStatus == 4">
          <span class="orange-normal">已下架（待支付）</span>
        </p>
      </template>

      <!-- 车主列自定义显示 -->
      <template slot-scope="{ row }" slot="Owner">
        <div>
          <p>{{ (row.ownerInfo && row.ownerInfo.nickname) || "未知车主" }}</p>
          <p v-if="row.ownerInfo && row.ownerInfo.phone">
            {{ row.ownerInfo.phone }}
          </p>
        </div>
      </template>

      <!-- 乘客列自定义显示 -->
      <template slot-scope="{ row }" slot="passenger">
        <div v-if="row.passengersInfo && row.passengersInfo.length > 0">
          <div v-for="(passenger, index) in row.passengersInfo" :key="index">
            <p>{{ (passenger && passenger.nickname) || "未知乘客" }}</p>
            <p v-if="passenger && passenger.phone">{{ passenger.phone }}</p>
          </div>
        </div>
        <div v-else>
          <p>未知乘客</p>
        </div>
      </template>
    </avue-crud>

    <!-- 聊天记录的弹框 -->
    <el-dialog
      title="聊天记录"
      :visible.sync="chatDialogVisible"
      width="60%"
      :before-close="handleChatDialogClose"
      custom-class="chat-dialog"
      :modal-append-to-body="false"
      append-to-body
    >
      <div class="chat-container">
        <!-- 用户信息区域 -->
        <div class="user-info-section">
          <div class="user-info">
            <h4>车主</h4>
            <p>{{ ownerInfo.nickname || "未知车主" }}</p>
            <p v-if="ownerInfo.phone">{{ ownerInfo.phone }}</p>
          </div>
          <div class="user-info">
            <h4>乘客</h4>
            <template v-if="passengersInfo.length > 0">
              <div v-for="(passenger, index) in passengersInfo" :key="index">
                <p>{{ (passenger && passenger.nickname) || "未知乘客" }}</p>
                <p v-if="passenger && passenger.phone">{{ passenger.phone }}</p>
              </div>
            </template>
            <p v-else>未知乘客</p>
          </div>
        </div>

        <!-- 搜索区域 -->
        <div class="search-section">
          <el-input
            v-model="searchKeyword"
            placeholder="请输入聊天内容"
            clearable
            @clear="handleSearchClear"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="handleSearchChat"
            ></el-button>
          </el-input>
        </div>

        <!-- 聊天内容区域 -->
        <div class="chat-content">
          <div v-if="chatMessages.length === 0" class="empty-message">
            <el-empty description="暂无聊天记录"></el-empty>
          </div>
          <div
            v-for="(message, index) in filteredMessages"
            :key="index"
            class="message-item"
            :class="{
              'owner-message': isOwnerMessage(message),
              'passenger-message': !isOwnerMessage(message),
            }"
          >
            <div class="message-header">
              <strong>{{ getMessageSenderName(message) }}</strong>
              <span class="message-time">{{
                formatTime(message.created_at)
              }}</span>
            </div>
            <div class="message-body">
              {{ message.content }}
            </div>
          </div>
        </div>

        <!-- 分页区域 -->
        <div class="pagination-section">
          <el-pagination
            @size-change="handleChatSizeChange"
            @current-change="handleChatPageChange"
            :current-page="chatCurrentPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="chatPageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalMessages"
          />
        </div>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import { mapGetters } from "vuex";
import { getlineList, getChatList } from "./api";

export default {
  data() {
    return {
      form: {},
      query: {},
      loading: false,
      searchInfo: {},
      page: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
      selectionList: [],
      option: {
        menuType: "button",
        height: "auto",
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: false,
        index: true,
        indexLabel: "序号",
        searchBtnText: "提交",
        searchBtnIcon: "提交",
        emptyBtnText: "重置",
        emptyBtnIcon: "重置",
        viewBtn: false,
        addBtn: false,
        addBtnText: "添加",
        addBtnIcon: "el-icon-plus",
        editBtn: false,
        editBtnText: "",
        selection: false,
        dialogClickModal: false,
        delBtn: false,
        delBtnText: "",
        labelWidth: 110,
        searchLabelWidth: 100,
        column: [
          {
            label: "路线",
            prop: "route",
            search: true,
          },
          {
            label: "出发时间",
            prop: "departureTime",
            type: "date",
            search: true,
          },
          {
            label: "车主",
            prop: "Owner",
            search: true,
          },
          {
            label: "乘客",
            prop: "passenger",
            search: true,
            hide: true,
            display: false,
          },
          {
            label: "车主类型",
            prop: "OwnerType",
            search: true,
            type: "select",
            dicData: [
              {
                label: "非营运车主",
                value: 1,
              },
              {
                label: "营运车主",
                value: 2,
              },
            ],
          },
          {
            label: "乘客总订座数",
            prop: "reservationsNumber",
          },
          {
            label: "单座价格",
            prop: "SinglePrice",
          },
          {
            label: "状态",
            prop: "ReviewStatus",
            search: true,
            type: "select",
            dicData: [
              {
                label: "进行中",
                value: 0,
              },
              {
                label: "已完成",
                value: 1,
              },
              {
                label: "已下架",
                value: 2,
              },
              {
                label: "已完成（待支付）",
                value: 3,
              },
              {
                label: "已下架（待支付）",
                value: 4,
              },
            ],
          },
          {
            label: "发布时间",
            prop: "ReviewTime",
          },
        ],
      },
      resData: [],
      currentItemData: null,
      // 聊天弹框相关数据
      chatDialogVisible: false,
      searchKeyword: "",
      chatMessages: [],
      chatCurrentPage: 1,
      chatPageSize: 10,
      totalMessages: 0,
      currentChatRow: null,
      ownerInfo: {},
      passengersInfo: [],
    };
  },
  computed: {
    ...mapGetters(["permission"]),

    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.user_add, true),
        viewBtn: this.vaildData(this.permission.user_view, true),
        delBtn: this.vaildData(this.permission.user_delete, true),
        editBtn: this.vaildData(this.permission.user_edit, true),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    filteredMessages() {
      if (!this.searchKeyword) {
        return this.chatMessages;
      }
      return this.chatMessages.filter((message) =>
        message.content.toLowerCase().includes(this.searchKeyword.toLowerCase())
      );
    },
  },
  methods: {
    // 格式化时间显示
    formatTime(time) {
      if (!time) return "";
      return time.replace("T", " ").substring(0, 19);
    },

    // 判断消息是否来自车主
    isOwnerMessage(message) {
      return message.from_uid === this.ownerInfo.id;
    },

    // 获取消息发送者名称
    getMessageSenderName(message) {
      if (message.from_uid === this.ownerInfo.id) {
        return this.ownerInfo.nickname || "车主";
      }

      // 查找乘客信息
      const passenger = this.passengersInfo.find(
        (p) => p.id === message.from_uid
      );
      return passenger ? passenger.nickname : "乘客";
    },

    // 详情相关
    handleView(data) {
      this.$router.push({
        path: "/itineraryManagement/detail",
        query: { id: data.id },
      });
    },

    beforeOpen(done, type) {
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },

    // 获取列表数据
    onLoad(page, search = {}) {
      this.loading = true;
      let param = {
        page: page.currentPage,
        size: page.pageSize,
        line_keyword: this.query.route,
        start_time_start: this.query.departureTime
          ? [this.query.departureTime][0]
          : undefined,
        start_time_end: this.query.departureTime
          ? [this.query.departureTime][1]
          : undefined,
        user_keyword: this.query.Owner,
        passenger_keyword: this.query.passenger,
        status: this.query.ReviewStatus,
        pay_status: this.query.payStatus,
      };

      // 移除值为undefined的参数
      Object.keys(param).forEach(
        (key) => param[key] === undefined && delete param[key]
      );

      getlineList(param)
        .then((res) => {
          const response = res.data;
          const listData =
            response.list || response.records || response.data || [];

          this.page.total = response.total || listData.length;

          this.resData = listData.map((item) => {
            // 预处理车主和乘客信息
            const { ownerInfo, passengersInfo } = this.extractUserInfo(item);

            return {
              id: item.id,
              line_id: item.line_id || item.id,
              route: `${item.start_name}-${item.end_name}`,
              departureTime: item.start_time,
              Owner: ownerInfo.nickname || "未知车主",
              OwnerType: item.car_owner_type,
              reservationsNumber: item.on_order + "座",
              SinglePrice: "￥" + item.unit_price,
              ReviewStatus: item.status,
              ReviewTime: item.created_at,
              ownerInfo,
              passengersInfo,
              rawData: item, // 保留原始数据
            };
          });

          this.loading = false;
          this.selectionClear();
        })
        .catch(() => {
          this.loading = false;
        });
    },

    // 从行数据中提取用户信息
    extractUserInfo(item) {
      let ownerInfo = {};
      let passengersInfo = [];

      // 1. 车主信息 - 从user_nickname和user_phone获取
      ownerInfo = {
        id: item.uid,
        nickname: item.user_nickname || "未知车主",
        phone: item.user_phone,
      };

      // 2. 乘客信息 - 从lineOrder数组中获取
      if (item.lineOrder && Array.isArray(item.lineOrder)) {
        passengersInfo = item.lineOrder
          .map((order) => {
            const user = order.user || {};
            return {
              id: order.uid,
              nickname: user.nickname || "未知乘客",
              phone: user.phone,
            };
          })
          .filter((p) => p.id !== ownerInfo.id); // 确保乘客不是车主
      }

      return { ownerInfo, passengersInfo };
    },

    // 打开聊天记录弹框
    handMessage(row) {
      this.currentChatRow = row;
      this.chatDialogVisible = true;
      this.chatCurrentPage = 1;
      this.searchKeyword = "";

      // 设置车主和乘客信息
      this.ownerInfo = row.ownerInfo || {};
      this.passengersInfo = row.passengersInfo || [];

      // 获取聊天记录
      this.fetchChatMessages();
    },

    // 获取聊天记录
    async fetchChatMessages() {
      try {
        this.loading = true;

        // 确定line_id - 优先使用line_id，如果没有则使用id
        const lineId = this.currentChatRow.line_id || this.currentChatRow.id;

        if (!lineId) {
          this.$message.warning("无法获取路线ID");
          return;
        }

        const res = await getChatList({
          line_id: lineId,
          page: this.chatCurrentPage,
          size: this.chatPageSize,
          keyword: this.searchKeyword,
        });

        const responseData = res.data || {};
        this.chatMessages = responseData.list || [];
        this.totalMessages = responseData.total || 0;

        // 如果聊天记录中有新的用户信息，更新显示
        if (this.chatMessages.length > 0) {
          this.updateUserInfoFromMessages();
        }
      } catch (error) {
        console.error("获取聊天记录失败:", error);
        this.$message.error("获取聊天记录失败");
      } finally {
        this.loading = false;
      }
    },

    // 从聊天消息中更新用户信息
    updateUserInfoFromMessages() {
      const firstMessage = this.chatMessages[0];

      // 如果消息中有用户信息，优先使用
      if (firstMessage.fromUser) {
        // 确定哪个是车主，哪个是乘客
        if (firstMessage.from_uid === this.ownerInfo.id) {
          this.ownerInfo = { ...this.ownerInfo, ...firstMessage.fromUser };
          if (firstMessage.toUser) {
            // 检查是否已经存在该乘客
            const existingPassenger = this.passengersInfo.find(
              (p) => p.id === firstMessage.toUser.id
            );
            if (!existingPassenger) {
              this.passengersInfo.push(firstMessage.toUser);
            }
          }
        } else {
          // 可能是乘客发的第一条消息
          const existingPassenger = this.passengersInfo.find(
            (p) => p.id === firstMessage.from_uid
          );
          if (!existingPassenger) {
            this.passengersInfo.push(firstMessage.fromUser);
          }
        }
      }
    },

    // 聊天弹框关闭
    handleChatDialogClose(done) {
      this.searchKeyword = "";
      this.chatCurrentPage = 1;
      this.chatMessages = [];
      this.ownerInfo = {};
      this.passengersInfo = [];
      done();
    },

    // 搜索聊天内容
    handleSearchChat() {
      this.chatCurrentPage = 1;
      this.fetchChatMessages();
    },

    // 清空搜索
    handleSearchClear() {
      this.searchKeyword = "";
      this.fetchChatMessages();
    },

    // 分页大小变化
    handleChatSizeChange(val) {
      this.chatPageSize = val;
      this.chatCurrentPage = 1;
      this.fetchChatMessages();
    },

    // 当前页变化
    handleChatPageChange(val) {
      this.chatCurrentPage = val;
      this.fetchChatMessages();
    },
  },
};
</script>

<style lang="scss" scoped>
.blue-normal {
  color: #0e77d1;
  display: inline-block;
  display: flex;
  align-items: center;

  &::before {
    content: "";
    display: inline-block;
    width: 10px;
    height: 10px;
    border-radius: 10px;
    background-color: #0e77d1;
    margin-right: 4px;
  }
}

.green-normal {
  color: #00a854;
  display: inline-block;

  &::before {
    content: "";
    display: inline-block;
    width: 10px;
    height: 10px;
    border-radius: 10px;
    background-color: #00a854;
    margin-right: 4px;
  }
}

.gray-normal {
  color: #aaaaaa;
  display: inline-block;

  &::before {
    content: "";
    display: inline-block;
    width: 10px;
    height: 10px;
    border-radius: 10px;
    background-color: #aaaaaa;
    margin-right: 4px;
  }
}

.purple-normal {
  color: #8400ff;
  display: inline-block;

  &::before {
    content: "";
    display: inline-block;
    width: 10px;
    height: 10px;
    border-radius: 10px;
    background-color: #8400ff;
    margin-right: 4px;
  }
}

.orange-normal {
  color: #f59a23;
  display: inline-block;

  &::before {
    content: "";
    display: inline-block;
    width: 10px;
    height: 10px;
    border-radius: 10px;
    background-color: #f59a23;
    margin-right: 4px;
  }
}

.chat-dialog {
  position: relative;
  z-index: 2000 !important;
  .el-dialog__body {
    padding: 0 20px;
  }

  .chat-container {
    display: flex;
    flex-direction: column;
    height: 600px;

    .user-info-section {
      display: flex;
      padding: 15px 0;
      border-bottom: 1px solid #ebeef5;

      .user-info {
        flex: 1;
        padding: 0 15px;

        h4 {
          margin: 0 0 10px 0;
          font-size: 16px;
          color: #333;
        }

        p {
          margin: 5px 0;
          font-size: 14px;
          color: #666;
        }
      }
    }

    .search-section {
      padding: 15px 0;

      .el-input {
        width: 100%;
      }
    }

    .chat-content {
      flex: 1;
      overflow-y: auto;
      padding: 10px 0;
      border-top: 1px solid #f0f0f0;
      border-bottom: 1px solid #f0f0f0;

      .empty-message {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100%;
      }

      .message-item {
        margin-bottom: 15px;
        padding: 10px 15px;
        background-color: #f5f5f5;
        border-radius: 4px;

        &.owner-message {
          background-color: #e6f7ff;
        }
        

        .message-header {
          display: flex;
          justify-content: space-between;
          margin-bottom: 5px;
          font-size: 14px;

          strong {
            color: #333;
          }

          .message-time {
            color: #999;
            font-size: 12px;
          }
        }

        .message-body {
          font-size: 14px;
          color: #666;
          line-height: 1.5;
        }
      }
    }

    .pagination-section {
      padding: 15px 0;
      text-align: right;
    }
  }
}

</style>
